/**
 * 文件上传组件
 * 依赖于jQuery、layui、layer、qiniu前后台
 * @param domId
 * @constructor
 */
var FileUploadUnit = function (domId) {
    /**
     * 配置
     */
    this.options = {
        elem: '#'+domId,
        url: AppComm.url.getBaseURL()+'/unit/ajax/qiniuSimulate4Upload',
        // 请求上传接口的额外参数。
        data: null,
        // 接口的请求头。如：headers: {token: 'sasasas'}。
        headers: null,
        // 指定允许上传时校验的文件类型，可选值有：images（图片）、file（所有文件）、video（视频）、audio（音频）
        accepts: "file",
        // 允许上传的文件类型 默认所有类型都可以(可选值有：images（图片）、file（所有文件）、video（视频）、audio（音频）)
        // 规定打开文件选择框时，筛选出的文件类型，值为用逗号隔开的 MIME 类型列表。如：
        // acceptMime: 'image/*'（只显示图片文件）
        // acceptMime: 'image/jpg, image/png'（只显示 jpg 和 png 文件）
        acceptMime: null,
        // 允许上传的文件后缀。一般结合 accept 参数类设定。假设 accept 为 file 类型时，那么你设置 exts: 'zip|rar|7z' 即代表只允许上传压缩格式的文件。如果 accept 未设定，那么限制的就是图片的文件格式
        exts: null,
        auto: false,
        bindAction: '#'+domId+'BindAction',
        field: null,
        size: 0,
        // 是否允许多文件上传。设置 true即可开启。
        multiple: false,
        // 设置同时可上传的文件数量，一般配合 multiple 参数出现。
        number: 0,
        // 是否接受拖拽的文件上传，设置 false 可禁用。
        drag: true,
        storage: 'qiniu',
        // 覆盖上传时文件在七牛上的key由filePrefix+fileName组成,如：catalogue/0a7027fe-2abf-47d9-bdad-6f3315d9524f.jpg
        filePrefix: '',
        fileName: '',
        // 多文件上传时显示上传文件的页面区域
        multipleFileListView:'#'+domId+'ListView'
    };

    var uploadObj = this.options;

    this.callbackFun = new Object();
    //选则文件后回调
    this.callbackFun.choose = null;
    this.callbackFun.before = null;
    //上传成功回调
    this.callbackFun.done = null;
    //上传错误回调
    this.callbackFun.uploadError = null;
    // 七牛的回调
    this.callbackFun.next = null;
    this.callbackFun.error = null;
    this.callbackFun.complete = null;

    var callback = this.callbackFun;

    this.singleFileInit = function () {
        layui.use(['upload'],function () {
            var upload = layui.upload;
            var uploadInst = upload.render({
                elem: uploadObj.elem,
                url: uploadObj.url,
                data: uploadObj.data,
                headers: uploadObj.headers,
                accept: uploadObj.accepts,
                acceptMime: uploadObj.acceptMime,
                exts: uploadObj.exts,
                auto: uploadObj.auto,
                bindAction: uploadObj.bindAction,
                field: uploadObj.field,
                size: uploadObj.size,
                multiple: false,
                number: uploadObj.number,
                drag: uploadObj.drag,
                choose: function(obj) {
                    obj.resultData = {};
                    obj.preview(function(index, file, result) {
                        obj.resultData.fileName = file.name;
                        // 异步变同步
                        call();
                    });

                    function call() {
                        if (typeof callback.choose === "function") {
                            callback.choose(obj);
                        }
                    }
                },
                before: function(obj){
                    //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
                    layer.load(); //上传loading

                    obj.preview(function(index, file, result) {
                        if (uploadObj.storage=='qiniu') {
                            // 使用七牛云对象存储
                            var fileName = file.name;
                            var suffix = fileName.substring(fileName.lastIndexOf("."),fileName.length);
                            var params = {
                                suffix: suffix,
                                filePrefix: uploadObj.filePrefix,
                                fileName: uploadObj.fileName
                            };
                            var onSuccess = function (resultData) {
                                if(resultData.success == 0){
                                    //设置上传过程的监听函数
                                    var observer = {
                                        next(res){
                                            //上传中(res参数带有total字段的 object，包含loaded、total、percent三个属性)
                                            //查看进度[loaded:已上传大小(字节);total:本次上传总大小;percent:当前上传进度(0-100)]
                                            console.log(Math.floor(res.total.percent));
                                            if (typeof callback.next === "function") {
                                                res.resultData = resultData;
                                                callback.next(res);
                                            }
                                        },
                                        error(err){
                                            //失败后
                                            layer.alert(err.message, {
                                                icon: 0,
                                                skin: 'layer-ext-moon'
                                            });
                                            layer.closeAll('loading');
                                            if (typeof callback.error === "function") {
                                                err.resultData = resultData;
                                                callback.error(err);
                                            }
                                        },
                                        complete(res){
                                            layer.closeAll('loading');
                                            //成功后
                                            // ?imageView2/2/h/100：展示缩略图，不加显示原图
                                            // ?vframe/jpg/offset/0/w/480/h/360：用于获取视频截图的后缀，0：秒，w：宽，h：高
                                            // imageView2({
                                            //     mode: 3,       // 缩略模式，共6种[0-5]
                                            //     w: 100,        // 具体含义由缩略模式决定
                                            //     h: 100,        // 具体含义由缩略模式决定
                                            //     q: 100,        // 新图的图像质量，取值范围：1-100
                                            //     format: 'png'  // 新图的输出格式，取值范围：jpg，gif，png，webp等
                                            // }
                                            // $("#image").attr("src",resultData.domain+"/"+resultData.imgUrl+"?imageView2/2/w/400/h/400/q/100");

                                            if (typeof callback.complete === "function") {
                                                res.resultData = resultData;
                                                callback.complete(res);
                                            }
                                        }
                                    };
                                    var putExtra = {
                                        fname: "",                          //原文件名
                                        params: {},                         //用来放置自定义变量
                                        mimeType: null                      //限制上传文件类型
                                    };
                                    var config = {
                                        region:qiniu.region.z2,             //存储区域(z0:代表华东;z2:代表华南,不写默认自动识别)
                                        concurrentRequestLimit:3            //分片上传的并发请求量
                                    };
                                    var observable = qiniu.upload(file,resultData.fileKey,resultData.token,putExtra,config);

                                    // 上传开始
                                    var subscription = observable.subscribe(observer);
                                    // 取消上传订阅,同时终止上传行为
                                    // subscription.unsubscribe();
                                }else{
                                    //获取凭证失败
                                    layer.alert(resultData.message, {
                                        icon: 0,
                                        skin: 'layer-ext-moon'
                                    });
                                }

                                // if (resultData.code==Enums.ResultEnum().SUCCESS.code) {
                                //     layer.msg("删除成功！", {icon: 1});
                                // }
                            };
                            AppComm.ajax.post('/unit/ajax/qiniuUpToken', params, onSuccess);
                        }
                        call();
                    });
                    function call() {
                        if (typeof callback.before === "function") {
                            callback.before(obj);
                        }
                    }
                },
                done: function (res, index, upload) {
                    // var resStr = JSON.stringify(res.data);
                    // if (typeof callback.doneCallback === "function") {
                    //     callback.doneCallback(index);
                    // } else {
                    //     layer.open({
                    //         type: 0,
                    //         title: '返回结果',
                    //         content: resStr
                    //     });
                    // }
                    if (uploadObj.storage!='qiniu') {
                        layer.closeAll('loading');
                    };
                    if (typeof callback.done === "function") {
                        callback.done(res, index, upload);
                    };
                },
                error: function (index, upload) {
                    //请求异常回调
                    // if (typeof callback.errorCallback === "function") {
                    //     callback.errorCallback(index);
                    // }
                    layer.closeAll('loading');
                    if (typeof callback.uploadError === "function") {
                        callback.uploadError(index, upload);
                    };
                }
            });
        });

    };

    this.multipleFileInit = function () {
        layui.use(['upload'], function () {
            var upload = layui.upload;
            var uploadInst = upload.render({
                elem: uploadObj.elem,
                url: uploadObj.url,
                data: uploadObj.data,
                headers: uploadObj.headers,
                accept: uploadObj.accepts,
                acceptMime: uploadObj.acceptMime,
                exts: uploadObj.exts,
                auto: uploadObj.auto,
                bindAction: uploadObj.bindAction,
                field: uploadObj.field,
                size: uploadObj.size,
                multiple: true,
                number: uploadObj.number,
                drag: uploadObj.drag,
                choose: function (obj) {

                    if (typeof callback.choose === "function") {
                        // 如果调用者有回调方法就用调用者的回调方法
                        callback.choose(obj);
                    } else {
                        var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                        //读取本地文件
                        obj.preview(function(index, file, result) {
                            var tr = $(['<tr id="upload-'+ index +'">'
                            ,'<td>'+ file.name +'</td>'
                            ,'<td>'+ (file.size/1014).toFixed(1) +'kb</td>'
                            ,'<td>'
                            // ,'<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                            ,'<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                            ,'</td>'
                            ,'</tr>'].join(''));

                            //单个重传
                            // tr.find('.demo-reload').on('click', function(){
                            //     obj.upload(index, file);
                            // });

                            //删除
                            tr.find('.demo-delete').on('click', function(){
                                delete files[index]; //删除对应的文件
                                tr.remove();
                                uploadInst.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                            });

                            $(uploadObj.multipleFileListView).append(tr);
                        });
                    }
                },
                before: function (obj) {
                    var files = this.files;
                    obj.preview(function(index, file, result) {
                        $.each(files,function(key,value){
                            if (value==file) {
                                if (uploadObj.storage=='qiniu') {
                                    layer.load(); //上传loading
                                    // 使用七牛云对象存储
                                    var fileName = file.name;
                                    var suffix = fileName.substring(fileName.lastIndexOf("."),fileName.length);
                                    var params = {
                                        suffix: suffix,
                                        filePrefix: uploadObj.filePrefix,
                                        fileName: uploadObj.fileName
                                    };
                                    var onSuccess = function (resultData) {
                                        if(resultData.success == 0){
                                            //设置上传过程的监听函数
                                            var observer = {
                                                next(res){
                                                    //上传中(res参数带有total字段的 object，包含loaded、total、percent三个属性)
                                                    //查看进度[loaded:已上传大小(字节);total:本次上传总大小;percent:当前上传进度(0-100)]
                                                    console.log(Math.floor(res.total.percent));
                                                    if (typeof callback.next === "function") {
                                                        res.resultData = resultData;
                                                        callback.next(res);
                                                    }
                                                },
                                                error(err){
                                                    //失败后
                                                    layer.alert(err.message, {
                                                        icon: 0,
                                                        skin: 'layer-ext-moon'
                                                    });
                                                    layer.closeAll('loading');
                                                    if (typeof callback.error === "function") {
                                                        err.resultData = resultData;
                                                        callback.error(err);
                                                    }
                                                },
                                                complete(res){
                                                    layer.closeAll('loading');
                                                    if (typeof callback.complete === "function") {
                                                        res.resultData = resultData;
                                                        callback.complete(res);
                                                    }
                                                }
                                            };
                                            var putExtra = {
                                                fname: "",                          //原文件名
                                                params: {},                         //用来放置自定义变量
                                                mimeType: null                      //限制上传文件类型
                                            };
                                            var config = {
                                                region:qiniu.region.z2,             //存储区域(z0:代表华东;z2:代表华南,不写默认自动识别)
                                                concurrentRequestLimit:3            //分片上传的并发请求量
                                            };
                                            var observable = qiniu.upload(file,resultData.fileKey,resultData.token,putExtra,config);

                                            // 上传开始
                                            var subscription = observable.subscribe(observer);
                                            // 取消上传订阅,同时终止上传行为
                                            // subscription.unsubscribe();
                                        }else{
                                            //获取凭证失败
                                            layer.alert(resultData.message, {
                                                icon: 0,
                                                skin: 'layer-ext-moon'
                                            });
                                        }
                                    };
                                    AppComm.ajax.execute({
                                        'url':AppComm.url.getBaseURL()+'/unit/ajax/qiniuUpToken',
                                        'data':params,
                                        'success':onSuccess
                                    });
                                }
                            }
                        })
                    });

                },
                done: function (res, index, upload) {
                    // var resStr = JSON.stringify(res.data);
                    // if (typeof callback.doneCallback === "function") {
                    //     callback.doneCallback(index);
                    // } else {
                    //     layer.open({
                    //         type: 0,
                    //         title: '返回结果',
                    //         content: resStr
                    //     });
                    // }
                    if (uploadObj.storage != 'qiniu') {
                        layer.closeAll('loading');
                    };
                    if (typeof callback.done === "function") {
                        callback.done(res, index, upload);
                    };
                },
                error: function (index, upload) {
                    layer.closeAll('loading');
                    if (typeof callback.uploadError === "function") {
                        callback.uploadError(index, upload);
                    };
                }
            });
        });
    }

};

FileUploadUnit.getQiniuUrl = function(res) {
    return res.resultData.domain+"/"+res.resultData.fileKey+"?imageView2/2/w/400/h/400/q/100;v="+AppComm.utils.random(1,10000);
};